import  useCountDown  from '@/hooks/useCountDown';
import { getLogin,getCode } from '@/store/actions/login';
import { LoginForm } from '@/types/data';
import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input';
import { AxiosError } from 'axios';
import { useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';

import styles from './index.module.scss'

const Login = () => {
    const {start, count} =useCountDown(5,()=>setSentable(true))
    const [sendable, setSentable] = useState(true)
    const history=useHistory<{ from: string } | undefined>()
    // const Location =useLocation<unknown>()
    const dispatch=useDispatch()
    const [form] = Form.useForm() //mobile给定的--获取表单实例
    const mobileRef = useRef<InputRef>(null)
    const onFinish=async(values:LoginForm)=>{//表单提交
    console.log(values);
    try{
        await dispatch(getLogin(values))
        // 登录成功提示
       Toast.show({
       content: '登录成功',
       duration: 600,
       afterClose: () => {
         if(history.location.state){
         return  history.replace(history.location.state.from)
         }
         // 返回首页
         history.push('/home')
       },
     })
    }catch(e){
        console.dir(e);
        const error = e as AxiosError<{message:string}>
        const content=error.response?.data.message || '登录超时'
        Toast.show({
            duration: 600,
            content
        })
     }
    }
    const sendCode=async()=>{ //发送验证码
      //点按钮拿到手机号码
      const mobile = form.getFieldValue('mobile')
      const arr = form.getFieldError('mobile')
      // console.log(arr,'arr');//当不输时或者输对时为空数组
      if(!mobile || arr.length>0) return mobileRef.current?.focus() //自动获取焦点
      // console.log(mobile);//获取到手机号
       try{
        await dispatch(getCode(mobile))
         setSentable(false)
         start()
        Toast.show({ content: '发送成功'})
       }catch(e){
        const error = e as AxiosError<{message:string}>    
        Toast.show({ content:error.response?.data.message})
       }
    }
  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form onFinish={onFinish} form={form}>
          <Form.Item className="login-item"
          name="mobile"
          rules={[
            { required: true, message: '请输入手机号' },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '手机号格式错误'
            }
          ]}
          >
            <Input placeholder="请输入手机号" ref={mobileRef} />
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={<span className="code-extra" onClick={sendable?sendCode:()=>{}}>{sendable?'发送验证码':count+'后获取'}</span>}
          >
            <Form.Item name="code" className="login-item"  rules={[{ required: true, message: '请输入验证码' }]}>
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>
          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login